import React, { useState, useEffect } from 'react';
import { Table, Button, Tag, Space, Card, Typography, message, Spin, Empty } from 'antd';
import { useNavigate } from 'react-router-dom';
import { materialOrderService } from '../../services/materialOrderService';
import { EyeOutlined, DownloadOutlined } from '@ant-design/icons';

const { Title } = Typography;

// 订单状态标签
const OrderStatusTag = ({ status }) => {
  let color = 'default';
  let text = '未知状态';
  
  switch (status) {
    case 'pending':
      color = 'warning';
      text = '待支付';
      break;
    case 'paid':
      color = 'success';
      text = '已支付';
      break;
    case 'completed':
      color = 'green';
      text = '已完成';
      break;
    case 'cancelled':
      color = 'error';
      text = '已取消';
      break;
    case 'refunded':
      color = 'volcano';
      text = '已退款';
      break;
    default:
      break;
  }
  
  return <Tag color={color}>{text}</Tag>;
};

const MaterialOrderList = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(true);
  const [orders, setOrders] = useState([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });

  // 获取用户订单列表
  const fetchOrders = async (page = 1, limit = 10) => {
    try {
      setLoading(true);
      const response = await materialOrderService.getUserOrders(page, limit);
      
      setOrders(response.orders);
      setPagination({
        current: page,
        pageSize: limit,
        total: response.total
      });
    } catch (error) {
      console.error('获取订单列表失败:', error);
      message.error('获取订单列表失败: ' + (error.message || '未知错误'));
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchOrders(pagination.current, pagination.pageSize);
  }, []);

  // 处理表格分页变化
  const handleTableChange = (pagination) => {
    fetchOrders(pagination.current, pagination.pageSize);
  };

  // 查看订单详情
  const viewOrderDetails = (orderNumber) => {
    navigate(`/material/order/${orderNumber}`);
  };

  // 下载材料
  const handleDownload = async (orderNumber) => {
    try {
      // 生成下载令牌
      const tokenResult = await materialOrderService.generateDownloadToken(orderNumber);
      
      if (tokenResult && tokenResult.downloadUrl) {
        // 打开下载链接
        window.open(tokenResult.downloadUrl, '_blank');
        message.success('开始下载材料');
      } else {
        message.error('获取下载链接失败');
      }
    } catch (error) {
      console.error('下载材料失败:', error);
      message.error('下载材料失败: ' + (error.message || '未知错误'));
    }
  };

  // 去支付
  const goToPayment = (orderNumber) => {
    navigate(`/material/payment/${orderNumber}`);
  };

  // 表格列定义
  const columns = [
    {
      title: '订单号',
      dataIndex: 'orderNumber',
      key: 'orderNumber',
      ellipsis: true,
    },
    {
      title: '材料名称',
      dataIndex: ['material', 'title'],
      key: 'materialTitle',
      ellipsis: true,
      render: (text, record) => record.material?.title || '未知材料'
    },
    {
      title: '金额',
      dataIndex: 'totalAmount',
      key: 'totalAmount',
      render: (amount) => `¥${amount}`
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => <OrderStatusTag status={status} />
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (date) => new Date(date).toLocaleString()
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="small">
          <Button 
            type="text" 
            icon={<EyeOutlined />} 
            onClick={() => viewOrderDetails(record.orderNumber)}
          >
            详情
          </Button>
          
          {(record.status === 'paid' || record.status === 'completed') && (
            <Button 
              type="text" 
              icon={<DownloadOutlined />} 
              onClick={() => handleDownload(record.orderNumber)}
            >
              下载
            </Button>
          )}
          
          {record.status === 'pending' && (
            <Button 
              type="link" 
              onClick={() => goToPayment(record.orderNumber)}
            >
              去支付
            </Button>
          )}
        </Space>
      ),
    },
  ];

  return (
    <Card className="material-orders-container">
      <Title level={3}>我的材料订单</Title>
      
      {loading ? (
        <div className="loading-container" style={{ textAlign: 'center', padding: '50px 0' }}>
          <Spin size="large" />
          <p>加载订单数据...</p>
        </div>
      ) : orders.length > 0 ? (
        <Table
          columns={columns}
          dataSource={orders}
          rowKey="orderNumber"
          pagination={pagination}
          onChange={handleTableChange}
          scroll={{ x: 'max-content' }}
        />
      ) : (
        <Empty 
          description="暂无订单记录" 
          image={Empty.PRESENTED_IMAGE_SIMPLE}
        />
      )}
    </Card>
  );
};

export default MaterialOrderList;